using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ShivamEMR.Model.Domain.UserDomain;
using ShivamEMR.Model.DataInterfaces.UsersDataInterf;
using ShivamEMR.Model;
using ShivamEMR.Model.DataInterfaces.UIDataInterf;
using ShivamEMR.Web.Models;
using System.Web.Script.Serialization;
//using ShivamEMR.Web.Areas.User.Models;

namespace ShivamEMR.Web.Areas.User.Controllers
{   
    public class UserRoleController : Controller
    {
		private readonly IUserRoleRepository userroleRepository;
       private readonly IUserRightGroupRepository userrightGroupRepository;
        private readonly IUserRightRepository userrightRepository;
		// If you are using Dependency Injection, you can delete the following constructor
        public UserRoleController() 
        {
            userroleRepository = Registry.RepositoryFactory.GetUserRoleRepository();
          userrightGroupRepository = Registry.RepositoryFactory.GetUserRightGroupRepository();
            userrightRepository = Registry.RepositoryFactory.GetUserRightRepository();
        }

        public UserRoleController(IUserRoleRepository userroleRepository,IUserRightRepository userrightrepo,IUserRightGroupRepository usrrightgrp)
        {
			this.userroleRepository = userroleRepository;
            this.userrightGroupRepository = usrrightgrp;
            this.userrightRepository = userrightrepo;
        }

        //
        // GET: /UserRole/
        [CustomAuthorizeAttribute(RequiredRight = "Admin")]
        public ViewResult Index()
        {
           // return View(userroleRepository.AllIncluding(userrole => userrole.Designations, userrole => userrole.Rights));
            return View(userroleRepository.All);
        }

        //
        // GET: /UserRole/Details/5
        [CustomAuthorizeAttribute(RequiredRight = "Admin")]
        public ViewResult Details(int id)
        {
            return View(userroleRepository.Find(id));
        }

         
        private JsTreeModel[] GetTreeData(UserRole role)
        {
            var urgroups = userrightGroupRepository.All.ToList();
            var tree = new JsTreeModel[urgroups.Count];

            for (int i = 0; i < urgroups.Count; i++)
            {
                tree[i] = new JsTreeModel()
                {
                    data = urgroups[i].Group,
                    attr = new JsTreeAttribute() { id = urgroups[i].ID.ToString() + "_Group" }
                };

                if (urgroups[i].Rights != null && urgroups[i].Rights.Count > 0)
                {
                    tree[i].children = new JsTreeModel[urgroups[i].Rights.Count];
                    for (int j = 0; j < urgroups[i].Rights.Count; j++)
                    {
                        bool status = false;
                        if (role != null && role.Rights != null && role.Rights.Any(r => r.ID == urgroups[i].Rights.ToList()[j].ID))
                            status = true;
                        tree[i].children[j] = new JsTreeModel()
                        {
                            data = urgroups[i].Rights.ToList()[j].Title,
                            attr = new JsTreeAttribute() { id = urgroups[i].Rights.ToList()[j].ID.ToString(), selected = status }
                        };
                    }
                }
            }
            return tree;
           // var rights=userrightRepository.All.ToList();
            //var tree = new JsTreeModel[rights.Count];
            //for  (int i=0;i<rights.Count;i++)
            //{
            //    bool status = false;
            //    if (role != null && role.Rights != null && role.Rights.Any(r => r.ID == rights[i].ID))
            //        status = true;
            //    tree[i] = new JsTreeModel()
            //    {
            //        data = rights[i].Title,
            //        attr = new JsTreeAttribute() { id=rights[i].ID.ToString(), selected=status }
            //    };
            //}
            //return tree;
        }

    
        //
        // GET: /UserRole/Create
        [CustomAuthorizeAttribute(RequiredRight = "Admin")]
        public ActionResult Create()
        {
           // ViewBag.PossibleMenuGroups = menuGroupRepository.All;
            ViewBag.PossibleRights = userrightRepository.All;

            var model = GetTreeData(null);
            string jsonModel = new JavaScriptSerializer().Serialize(model);
            ViewBag.jsonModel = jsonModel;

            return View();
        } 

        //
        // POST: /UserRole/Create
        [CustomAuthorizeAttribute(RequiredRight = "Admin")]
        [HttpPost]
        public ActionResult Create(UserRole userrole)
        {
            foreach (var k in Request.Form.AllKeys.Where(k => k.StartsWith("check")&& !k.Contains("Group")))
            {
                var right = userroleRepository.GetAllRights().Where(r => r.ID == Convert.ToInt32(Request.Form[k])).Single();
                if (right != null)
                {
                    if (userrole.Rights == null) userrole.Rights = new List<UserRight>();
                    userrole.Rights.Add(right);
                }
            }
            if (ModelState.IsValid) {
                userroleRepository.Create(userrole);
                userroleRepository.Save();
                return RedirectToAction("Index");
            } else {
                ViewBag.PossibleMenuGroups = userrightGroupRepository.All;
                ViewBag.PossibleRights = userrightRepository.All;
                var model = GetTreeData(userrole);
                string jsonModel = new JavaScriptSerializer().Serialize(model);
                ViewBag.jsonModel = jsonModel;
				return View();
			}
        }
        
        //
        // GET: /UserRole/Edit/5
 [CustomAuthorizeAttribute(RequiredRight = "Admin")]
        public ActionResult Edit(int id)
        {
           ViewBag.PossibleMenuGroups = userrightGroupRepository.All;
            ViewBag.PossibleRights = userrightRepository.All;

            var model = GetTreeData(userroleRepository.Find(id));
            string jsonModel = new JavaScriptSerializer().Serialize(model);
            ViewBag.jsonModel = jsonModel;           
          return View(userroleRepository.Find(id));
        }

        //
        // POST: /UserRole/Edit/5
        [CustomAuthorizeAttribute(RequiredRight = "Admin")]
        [HttpPost]
        public ActionResult Edit(UserRole userrole)
        {
            userrole = userroleRepository.Find(userrole.ID);
            if (userrole != null && userrole.Rights != null)
            userrole.Rights.Clear();
            foreach (var k in Request.Form.AllKeys.Where(k => k.StartsWith("check") && !k.Contains("Group")))
            {               
                var right = userroleRepository.GetAllRights().Where(r=>r.ID==Convert.ToInt32( Request.Form[k])).Single();               
                if (right != null)
                {
                    if (userrole.Rights == null) userrole.Rights = new List<UserRight>();                     
                    userrole.Rights.Add(right);
                }                 
            }
            if (ModelState.IsValid) {
                userroleRepository.Update(userrole);
                userroleRepository.Save();
                return RedirectToAction("Index");
            }
            else
            {
             ViewBag.PossibleMenuGroups = userrightGroupRepository.All;
                ViewBag.PossibleRights = userrightRepository.All;
                var model = GetTreeData(userrole);
                string jsonModel = new JavaScriptSerializer().Serialize(model);
                ViewBag.jsonModel = jsonModel;
				return View();
			}
        }

        

        //
        // GET: /UserRole/Delete/5
 [CustomAuthorizeAttribute(RequiredRight = "Admin")]
        public ActionResult Delete(int id)
        {
            return View(userroleRepository.Find(id));
        }

        //
        // POST: /UserRole/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
           // userroleRepository.Delete(id);
            var role = userroleRepository.Find(id);
            userroleRepository.Delete(role);
            userroleRepository.Save();

            return RedirectToAction("Index");
        }
    }
}

